package model

import (
	"ginblog/utils/errmsg"
	"github.com/jinzhu/gorm"
)

type Category struct {
	ID   uint   `gorm:"primary_key;auto_increment" json:"id"`
	Name string `grom:"type:varchar(20);not null" json:"name"`
}

//查询分类是否存在
func CheckCategory(name string) (code int) {
	var cate Category
	db.Debug().Select("id").Where("name = ?", name).Find(&cate)
	if cate.ID > 0 {
		return errmsg.ERROR_CATEGORY_USED
	}
	return errmsg.SUCCSE
}

//新增分类
func CreateCategory(data *Category) int {
	if err := db.Create(&data).Error; err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCSE
}

//查询单个分类的信息
func GetCateInfo(id int) (Category, int) {
	var cate Category
	db.Where("id = ?", id).First(&cate)
	return cate, errmsg.SUCCSE
}

//查询分类列表
func GetCateList(pageSize int, pageNum int) ([]Category, int) {
	var cate []Category
	var total int
	err = db.Find(&cate).Count(&total).Limit(pageSize).Offset((pageNum - 1) * pageSize).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, 0
	}
	return cate, total
}

//修改分类
func UpdateCategory(id int, data *Category) int {
	var maps = make(map[string]interface{})
	maps["name"] = data.Name
	if err = db.Debug().Model(&Category{}).Where("id = ?", id).Update(maps).Error; err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCSE
}

//删除分类
func DeleteCategory(id int) int {
	var cate Category
	if err = db.Debug().Where("id = ?", id).Delete(&cate).Error; err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCSE
}
